package com.live.shop;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;

import com.live.shop.home.HomeActivity;
import com.live.shop.home.setting.PermissionActivity;
import com.live.shop.model.UserModel;
import com.live.shop.scene.client.WsHomeClientActivity;
import com.live.shop.sql.UserDatabase;
import com.live.shop.tool.GetUtil;
import com.live.shop.tool.OkHttpUtils;
import com.live.shop.tool.StatusBarUtils;
import com.live.shop.view.ToastBottomUtils;
import com.live.shop.view.ToastUtils;

import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Response;

public class LoginActivity extends BaseActivity {
    TextView login_button;
    TextView register_button;
    TextView login_client_button;
    EditText login_password;
    EditText login_account;
    UserDatabase userDb;
    UserModel userModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        StatusBarUtils.setDarkStatusWhite(this,R.color.white);
        login_account = findViewById(R.id.login_account);
        login_password = findViewById(R.id.login_password);
        login_button = findViewById(R.id.login_button);
        register_button = findViewById(R.id.register_button);
        login_client_button = findViewById(R.id.login_client_button);

        userDb = new UserDatabase(getApplicationContext());
        init();
    }
    public void init(){
        userModel = userDb.select();
        if(userModel.getAccount() != null){
            if(userModel.getStatus() != 1){
                getChangeDeviceDialog(userModel.getStatus());
            }

            login_account.setText(userModel.getAccount());
            login_password.setText(userModel.getPassword());
        }
        register_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        login_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(login_account.getText().toString().isEmpty() || login_password.getText().toString().isEmpty()){
                    ToastUtils.Setinfo(getApplicationContext(),"请输入账号密码",2);
                    return ;
                }
                try {
                    JSONObject appJson = GetUtil.getAppInfo(getApplicationContext());
                    JSONObject json = new JSONObject();
                    json.put("user_name",login_account.getText().toString());
                    json.put("user_password",login_password.getText().toString());
                    json.put("app_info",appJson);
                    getAccount(GetUtil.userPassLogin(),json.toString());
                    login_button.setClickable(false);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });
        login_client_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                    //读写(高版本)
                    if(!Environment.isExternalStorageManager()){
                        ToastBottomUtils.Setinfo(getApplicationContext(),"请授权【读写】权限！");
                        startActivity(new Intent(getApplicationContext(), PermissionActivity.class));
                        return;
                    }
                }else{
                    //低版本
                    if(ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ||
                            ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
                        ToastBottomUtils.Setinfo(getApplicationContext(),"请授权【读写】权限！");
                        startActivity(new Intent(getApplicationContext(), PermissionActivity.class));
                        return;
                    }
                }
                if(ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED){
                    ToastBottomUtils.Setinfo(getApplicationContext(),"请授权【摄像头】权限！");
                    startActivity(new Intent(getApplicationContext(), PermissionActivity.class));
                    return;
                }
                if(ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WAKE_LOCK) != PackageManager.PERMISSION_GRANTED){
                    ToastBottomUtils.Setinfo(getApplicationContext(),"请授权【控制屏幕锁定】权限！");
                    startActivity(new Intent(getApplicationContext(), PermissionActivity.class));
                    return;
                }
                WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
                if (!wifiManager.isWifiEnabled()){
                    ToastBottomUtils.Setinfo(getApplicationContext(),"未连接WIFI");
                    return;
                }
                startActivity(new Intent(getApplicationContext(), WsHomeClientActivity.class));
            }
        });
    }
    private void getChangeDeviceDialog(int status){
        final AlertDialog dialog = new AlertDialog.Builder(this).create();
        dialog.setCancelable(false);
        dialog.show();
        Window window = dialog.getWindow();
        assert window != null;
        window.setContentView(R.layout.dialog_home);

        final TextView title = window.findViewById(R.id.dialog_home_title);
        final TextView neirong = window.findViewById(R.id.dialog_home_neirong);
        final TextView close = window.findViewById(R.id.dialog_home_close);
        final TextView xiangqing = window.findViewById(R.id.dialog_home_xiangqing);
        switch (status){
            case -100:title.setText("会员到期");neirong.setText("您的账号会员权限已到期，如有疑问，请联系客服。");break;
            case -200:title.setText("禁止登录");neirong.setText("您的账号已限制登录，如有疑问，请联系客服。");break;
            case -300:title.setText("登录认证失效");neirong.setText("请重新登录。");break;
            case -400:title.setText("登录认证无效");neirong.setText("您的账号已在其他设备上通过账号密码登录，如果这不是您的操作，您的账号密码已经泄露，您可登录后修改账户密码。");break;
            case -500:title.setText("登录认证超时");neirong.setText("请重新登录。");break;
            default:title.setText("其他原因");neirong.setText("请重新登录。");break;
        }
        close.setVisibility(View.GONE);
        xiangqing.setText("确定");
        xiangqing.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                userDb.restoreStatus();
                dialog.cancel();
            }
        });
    }
    public static final int RRQUEST_FAILURE = 1;
    public static final int RRQUEST_SUCCESS = 2;
    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case RRQUEST_FAILURE:
                    ToastBottomUtils.Setinfo(getApplicationContext(),msg.obj.toString());
                    login_button.setClickable(true);
                    break;
                case RRQUEST_SUCCESS:
                    try {
                        JSONObject json = new JSONObject(msg.obj.toString());
                        if(json.getInt("code") == 1){
                            //登录成功
                            JSONObject valueJson = json.getJSONObject("data");
                            if(userModel.getAccount() != null){
                                //存在该账号
                                userDb.updateUserData(valueJson.getInt("uuid"),
                                        login_account.getText().toString(),
                                        login_password.getText().toString(),
                                        valueJson.getString("token"),
                                        valueJson.getString("endtime"),
                                        valueJson.getString("nickname"));
                            }else{
                                //不存在
                                userDb.insert(valueJson.getInt("uuid"),
                                        login_account.getText().toString(),
                                        login_password.getText().toString(),
                                        valueJson.getString("token"),
                                        valueJson.getString("endtime"),
                                        valueJson.getString("nickname"));
                            }
                            startActivity(new Intent(getApplicationContext(), HomeActivity.class));
                            finish();
                        }else{
                            //登录失败
                            ToastBottomUtils.Setinfo(getApplicationContext(),json.getString("info"));
                            login_button.setClickable(true);
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    break;
            }
        }
    };
    public void getAccount(String url,String jsonStr){
        OkHttpUtils.sendOkHttpJsonRequest(url, jsonStr,new okhttp3.Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Message message = new Message();
                message.what = RRQUEST_FAILURE;
                message.obj = "【请求异常】请联系管理员";
                handler.sendMessage(message);
            }
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String responseData = response.body().string();
                Message message = new Message();
                message.what = RRQUEST_SUCCESS;
                message.obj = responseData;
                handler.sendMessage(message);
            }
        });
    }
}